package com.xhj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import com.xhj.entity.Order;
import com.xhj.entity.PayLog;
import com.xhj.mapper.PayLogMapper;
import com.xhj.service.OrderService;
import com.xhj.service.PayLogService;
import com.xhj.util.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 支付日志表(TPayLog)表服务实现类
 *
 * @author makejava
 * @since 2021-03-11 13:22:24
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper,PayLog> implements PayLogService {

    @Autowired
    private OrderService orderService;

    @Override
    public Map<String, Object> createNative(String orderNo) {
        try {
            // 根据orderNo获取订单
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_no",orderNo);
            Order order = orderService.getOne(queryWrapper);
            if (order == null) throw new RuntimeException("未查到该订单信息！");
            // 调用统一下单API
            /*Map<String, Object> map = new HashMap<>();
            map.put("appid","wx74862e0dfcf69954");
            map.put("mchid","1558950191");
            map.put("description",order.getCourseTitle());
            map.put("out_trade_no",orderNo);
            map.put("notify_url","http://guli.shop/api/order/weixinPay/weixinNotify");
            Map<String, Object> amount = new HashMap<>();
            amount.put("total",order.getTotalFee().multiply(new BigDecimal(100)).longValue());
            amount.put("currency","CNY");
            map.put("amount", amount);
            try {
                HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/native");
                // 请求body参数
                String reqdata = "{"
                        + "\"time_expire\":\"2018-06-08T10:34:56+08:00\","
                        + "\"amount\": {"
                        + "\"total\":100,"
                        + "\"currency\":\"CNY\""
                        + "},"
                        + "\"mchid\":\"1230000109\","
                        + "\"description\":\"Image形象店-深圳腾大-QQ公仔\","
                        + "\"notify_url\":\"https://www.weixin.qq.com/wxpay/pay.php\","
                        + "\"out_trade_no\":\"1217752501201407033233368018\","
                        + "\"goods_tag\":\"WXG\","
                        + "\"appid\":\"wxd678efh567hg6787\","
                        + "\"attach\":\"自定义数据说明\","
                        + "\"detail\": {"
                        + "\"invoice_id\":\"wx123\","
                        + "\"goods_detail\": ["
                        + "{"
                        + "\"goods_name\":\"iPhoneX 256G\","
                        + "\"wechatpay_goods_id\":\"1001\","
                        + "\"quantity\":1,"
                        + "\"merchant_goods_id\":\"商品编码\","
                        + "\"unit_price\":828800"
                        + "},"
                        + "{"
                        + "\"goods_name\":\"iPhoneX 256G\","
                        + "\"wechatpay_goods_id\":\"1001\","
                        + "\"quantity\":1,"
                        + "\"merchant_goods_id\":\"商品编码\","
                        + "\"unit_price\":828800"
                        + "}"
                        + "],"
                        + "\"cost_price\":608800"
                        + "},"
                        + "\"scene_info\": {"
                        + "\"store_info\": {"
                        + "\"address\":\"广东省深圳市南山区科技中一道10000号\","
                        + "\"area_code\":\"440305\","
                        + "\"name\":\"腾讯大厦分店\","
                        + "\"id\":\"0001\""
                        + "},"
                        + "\"device_id\":\"013467007045764\","
                        + "\"payer_client_ip\":\"14.23.150.211\""
                        + "}"
                        + "}";
                StringEntity entity = new StringEntity(reqdata);
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
                httpPost.setHeader("Accept", "application/json");

                HttpClient httpClient = OrderUtil.initHttpClient();
                //完成签名并执行请求
                CloseableHttpResponse response = httpClient.execute(httpPost);

                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) { //处理成功
                    System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
                } else if (statusCode == 204) { //处理成功，无返回Body
                    System.out.println("success");
                } else {
                    System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
                    throw new IOException("request failed");
                }
            }catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }*/
            Map<String,String> m = new HashMap<>();
            //1、设置支付参数
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            m.put("body", order.getCourseTitle());
            m.put("out_trade_no", orderNo);
            m.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            m.put("spbill_create_ip", "127.0.0.1");
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            m.put("trade_type", "NATIVE");
            //2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //4、封装返回结果集
            Map<String,Object> map = new HashMap<>();
            map.put("out_trade_no", orderNo);
            map.put("course_id", order.getCourseId());
            map.put("total_fee", order.getTotalFee());
            map.put("result_code", resultMap.get("result_code"));
            map.put("code_url", resultMap.get("code_url"));
            //微信支付二维码2小时过期，可采取2小时未支付取消订单
            //redisTemplate.opsForValue().set(orderNo, map, 120, TimeUnit.MINUTES);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("生成支付二维码失败！");
        }

    }

    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {
            // 封装参数
            Map<String,String> m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            // 设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            // 返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            // 转成Map返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void updatePayStatus(Map<String, String> resultMap) {
        // 获取订单号
        String orderNo = resultMap.get("out_trade_no");
        //根据订单id查询订单信息
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no",orderNo);
        Order order = orderService.getOne(queryWrapper);
        if (order.getStatus() == 1) return;
        order.setStatus(1);
        orderService.updateById(order);
        // 记录支付日志
        PayLog payLog = new PayLog();
        payLog
                .setOrderNo(orderNo)
                .setPayTime(new Date())
                .setTotalFee(order.getTotalFee())
                .setTransactionId(resultMap.get("transaction_id"))
                .setTradeState(resultMap.get("trade_state"))
                .setPayType(1)
                .setAttr(JSONObject.toJSONString(resultMap));
        baseMapper.insert(payLog);
    }
}